import random

from django.http import JsonResponse
from django.http import HttpResponse
from apps.users.models import User
from libs.yuntongxun.yuntongxun.sms1 import CCP
from django.shortcuts import render
from django.views import View
# 生成验证码第三方包,直接将 captcha 包复制到项目 libs 目录下
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import celery_send_sms_code
# Create your views here.
# 1 图片验证码
class ImageCodeView(View):
    def get(self,request,uuid):
        text,image = captcha.generate_captcha()
        # 将验证码保存到setting里 Redis  2号库
        redis_cli = get_redis_connection('code')
        redis_cli.setex(uuid,100,text)
        return HttpResponse(image,content_type = 'image/jpg')

# 2 短信验证码
class SmsCodeView(View):
    def get(self,request,mobile):
        # 接收参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code,uuid]):
            return JsonResponse({'code': 400,'errmsg':'参数不全'})

        redis_cli = get_redis_connection('code')
        redis_image_code = redis_cli.get(uuid)

        if redis_image_code == None:
            return JsonResponse({'code':400,'errmsg':'验证码错误'})
        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse({'code':400,'errmsg':'验证码错误'})
        # if User.objects.filter(mobile = mobile).count() >= 1:
        #     return JsonResponse({'code':400,'errmsg':'手机号已注册'})

        # 3 标记位短信状态判断
        send_flag = redis_cli.get('send_flag_%s' % mobile)
        if send_flag is not None:
            return JsonResponse({'code':400,'errmsg':'请勿在60秒内发送验证码'})

        # 4 随机生成6位验证码
        sms_code = '%06d' % random.randint(0,999999)

        # 5 保存验证码
        # redis_cli.setex(mobile,300, sms_code)

        # 1 创建管道
        # 2 管道收集命令
        # 3 管道执行命令
        pipeline = redis_cli.pipeline()
        pipeline.setex(mobile,300,sms_code)
        pipeline.setex('send_flag_%s' % mobile,60,1)
        pipeline.execute()

        # 6 设置短信发送状态的标记位有效期为60秒
        redis_cli.setex('send_flag_%s' % mobile,60,1)

        # 7 发送验证码
        # CCP().send_template_sms(mobile,[sms_code,"5"],1)


        '''
        pip install celery
        # cmd 命令行中启动 celery -A celery_tasks.main worker -l INFO
        
        celery 4.0+ 版本不支持windows的进程任务调度 需要使用协程完成
        上面的命令适用与 linux&macOS

        pip install eventlet
        windows 执行命令：celery -A celery_tasks.main worker -l INFO -P eventlet -c 1000  (1000代表线程数)
        '''
        celery_send_sms_code.delay(mobile,sms_code)


        # 8返回响应
        return JsonResponse({'code':0,'errmsg':'ok'})













